<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="广告主id" prop="advertiserIdStr">
              <el-input v-model="queryParams.advertiserIdStr" placeholder="请输入广告主id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="广告主名称" prop="advertiserName">
              <el-input v-model="queryParams.advertiserName" placeholder="请输入广告主名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <!-- <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oce:advertiser:add']">新增</el-button> -->
            <el-button type="danger" plain icon="Delete" @click="clearAccount">清空已选</el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oce:advertiser:add']">新增</el-button> -->
            <el-button type="primary" plain icon="Plus" @click="handleAddBatch" v-hasPermi="['oce:project:batchAdd']">批量新建</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="multiple" @click="editAdvertiser()" v-hasPermi="['oce:advertsier:edit']"
              >修改头像</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oce:advertiser:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oce:advertiser:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:advertiser:export']">导出</el-button>
          </el-col> -->
          <div class="flex items-center text-[12px] tips">
            <div class="ml-[10px] label">当前操作帐户：</div>
            <div class="val" :class="appStore.accountName ? 'text-[#409EFF]' : 'text-[#f00]'">{{ appStore.accountName || '未设置' }}</div>
          </div>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="tableRef" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" row-key="advertiserId">
        <el-table-column type="selection" width="55" align="center" reserve-selection />
        <el-table-column label="广告主名称" align="left" width="300" prop="advertiserName" />
        <el-table-column label="广告主ID" align="left" prop="advertiserId"> </el-table-column>
        <!--        <el-table-column label="广告主公司名称" align="center" prop="advCompanyName" />-->
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oce:advertiser:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改橙子建站落地页对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="siteFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告主id" prop="advertiserId">
          <el-input v-model="form.advertiserId" placeholder="请输入广告主id" />
        </el-form-item>
        <el-form-item label="广告主名称" prop="advertiserName">
          <el-input v-model="form.advertiserName" placeholder="请输入广告主名称" />
        </el-form-item>
        <el-form-item label="广告主公司名称" prop="advCompanyName">
          <el-input v-model="form.advCompanyName" placeholder="请输入广告主公司名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Advertiser" lang="ts">
import { useAppStore } from '@/store/modules/app';
import { AdvertiserForm, AdvertiserVo, AdvertiserQuery } from '@/api/advertisement/advertiser/types';
import { listData, updateAdvertiserAvatar } from '@/api/advertisement/advertiser';
import { confirmPromote } from '@/utils/index';

type Router = Array<{
  path: string;
  title: string[];
}>;
type SelectAccountType = {
  id: number | string;
  name: string;
};
const selectAccount = ref<SelectAccountType[]>([]);
const router = useRouter();

const appStore = useAppStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const selectedRows = ref([]);
const tableRef = ref();

const dataList = ref<AdvertiserVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const siteFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AdvertiserForm = {
  accountId: undefined,
  advertiserId: undefined,
  advertiserName: undefined
};

const data = reactive<PageData<AdvertiserForm, AdvertiserQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    advertiserId: undefined,
    advertiserName: undefined,
    params: {}
  },
  rules: {
    accountId: [{ required: true, message: '管家账号id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const clearAccount = async () => {
  // await confirmPromote({ 'content': '确认清除吗？' });
  tableRef.value?.clearSelection();
  getList();
};

const editAdvertiser = (row: AdvertiserVo) => {
  ElMessageBox.confirm('是否修改头像?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      updateAdvertiserAvatar({ advertiserIds: ids.value, accountId: appStore.accountId }).then((res) => {
        if (res.code === 200) {
          proxy?.$modal.msgSuccess('修改成功');
          getList();
          tableRef.value.clearSelection();
        } else {
          proxy?.$modal.msgError(res.msg);
        }
      });
    })
    .catch(() => {});
};
const getList = async () => {
  loading.value = true;
  const res = await listData(queryParams.value);
  dataList.value = res.rows;
  selectedRows.value.map((infoItem) => {
    const rowToSelect = dataList.value.find((item) => item.advertiserId === infoItem.advertiserId);
    if (rowToSelect && tableRef.value) {
      tableRef.value.toggleRowSelection(rowToSelect, true);
    }
  });
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  siteFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdvertiserVo[]) => {
  selectedRows.value = selection;
  // if (selection.length > 1) {
  //   // 取消之前的选择
  //   tableRef.value.clearSelection();
  //   // 只保留最后一个选择
  //   tableRef.value.toggleRowSelection(selection[selection.length - 1]);
  //   selectedRows.value = selection[selection.length - 1];
  // } else {
  //   selectedRows.value = selection.length ? selection[0] : null;
  // }
  ids.value = selection.map((item) => item.advertiserId);
  selectAccount.value = selection.map((item: AdvertiserVo) => {
    return { id: item.advertiserId, name: item.advertiserName };
  });
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  // reset();
  // dialog.visible = true;
  // dialog.title = "添加橙子建站落地页";
};

const handleAddBatch = () => {
  if (ids.value.length === 0) {
    proxy?.$modal.msgError('请选择广告主');
    return;
  }

  const value = encodeURIComponent(JSON.stringify(selectAccount.value));
  router.push({ path: 'batchadd', query: { ids: value } });
};

onMounted(() => {
  getList();
});
</script>
